package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.audit.baidu.BaiduImageScan;
import com.heima.audit.baidu.BaiduTextScan;
import com.heima.file.service.FileStorageService;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.config.RabbitMqConfig;
import com.heima.wemedia.entry.Item;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.AuditService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description AuditServiceImpl
 * @Author dmx
 * @Date 2024-11-26
 */
//审核接口
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private BaiduImageScan baiduImageScan;

    @Autowired
    private BaiduTextScan baiduTextScan;


    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMapper vmNewMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 审核文本和图片
     *
     * @param wmNews
     * @return
     */
    @Async//标明该方法要异步调用
    public void AuditImageAndText(WmNews wmNews) {

        String images = wmNews.getImages();
        List<Integer> list = new LinkedList<>();

        if (!StringUtils.isBlank(images)) {
            String[] split = images.split(",");
            for (String s : split) {
                byte[] bytes = fileStorageService.downLoadFile(s);
                Integer integer = baiduImageScan.imageScan(bytes);
                list.add(integer);
            }
        }

        String text = getText(wmNews.getContent());
        Integer integer = baiduTextScan.textScan(text);//判断文本是否违规
        Integer titleInteger = baiduTextScan.textScan(wmNews.getTitle());//判断标题是否违规

        //将两者的状态integer、titleInteger都存入集合
        list.add(integer);
        list.add(titleInteger);
        LambdaUpdateWrapper<WmNews> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(WmNews::getId, wmNews.getId());

        // list.forEach(System.out::println);
        //判断
        //有一个内容不合规，则整个内容不合规
        if (list.contains(2) || list.contains(4)) {
            //wmNews.setStatus((short) 2);
            wrapper.set(WmNews::getStatus, (short) 2);
            vmNewMapper.update(null, wrapper);
        } else if (!list.contains(2) && !list.contains(4) && !list.contains(1)) {
//           wmNews.setStatus((short) 3);
//           vmNewMapper.update(wmNews,wrapper);
            wrapper.set(WmNews::getStatus, (short) 3);
            vmNewMapper.update(null, wrapper);
        } else if (!list.contains(2) && !list.contains(3) && !list.contains(4)) {
//           wmNews.setStatus((short) 8);
//           vmNewMapper.update(wmNews,wrapper);
            wrapper.set(WmNews::getStatus, (short) 8);
            vmNewMapper.update(null, wrapper);

            //将消息发送给死信交换机处理
            //获取发布时间和文章id
            Date publishTime = wmNews.getPublishTime();
            Date date = new Date();
            Long interval = 0l;
            if (publishTime.getTime() - date.getTime()<=0) {
                interval = 0l;
            } else {
                interval = publishTime.getTime() - date.getTime();
            }
            Integer id = wmNews.getId();
            //生产消息
            String message = StringUtils.toStringTrim(id);//将id转换为字符串
            Message msg = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8))
                    .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                    .setExpiration(interval.toString()).build();
            rabbitTemplate.convertAndSend(RabbitMqConfig.TTL_EXCHANGE, RabbitMqConfig.TTL_ROUTE_KEY, msg);

        }

    }


    private String getText(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        String text = "";
        try {
            List<Item> items = objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, Item.class));

            // 提取所有 type 为 "text" 的 value 值
            List<String> textValues = items.stream()
                    .filter(item -> "text".equals(item.getType()))
                    .map(Item::getValue)
                    .collect(Collectors.toList());
            for (String textValue : textValues) {
                text += textValue;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }

}
